import {
    observable,
    action,
    computed,
    runInAction,
    toJS
} from 'mobx';
import BaseStore from '../BaseStore';

// ruleType取值
const USER_DATA_RULE = 1; // 用户列表
const ORGANIZATION_DATA_RULE = 2; // 组织结构
const MATERIAL_DATA_RULE = 3; // 物资列表
const MATERIAL_ORGANIZATION_RELATION_DATA_RULE = 4; // 物资组织机构关联
const MANAGE_SCHEDULE = 5; // 排班管理

class Store extends BaseStore {
    // 权限配置项集合
    @observable _dataRules;
    // 所有角色
    @observable _roles;
    // 组织机构树
    @observable _organizationTree;
    // 一级人员分组
    @observable _firstUserGroup;
    // 二级人员分组
    @observable _secondUserGroups;
    // 一级物资分组
    @observable _firstMaterialGroup;
    // 二级物资分组
    @observable _secondMaterialGroups;
    // 物资类型
    @observable _categories;

    ruleType;
    resourceId;
    resourceName;
    bizCode;
    // categoryId;

    // 数据模板
    generateNewDataRuleItem() {
        let targetDataRuleType = 3;
        if (this.ruleType === MATERIAL_DATA_RULE) {
            targetDataRuleType = 2;
        } else if (this.ruleType === ORGANIZATION_DATA_RULE || this.ruleType === MATERIAL_ORGANIZATION_RELATION_DATA_RULE) {
            targetDataRuleType = 4;
        }
        return {
            data_rule_person: {
                data_rule_type: 1,
                role_ids: [-1],
                type: 1,
                dep_ids: [],
                material_group: [{
                    first_group_id: -1,
                    second_group_id: -1,
                }],
            },
            data_rule_material: {
                data_rule_type: targetDataRuleType,
                is_manager_default_dept: 2,
                type: 1,
                dep_ids: [],
                material_group: [{
                    first_group_id: -1,
                    second_group_id: -1,
                }],
                data_rule_material_ext: [{
                    category_id: -1,
                    attr_id: -1,
                    attr_option_ids: [],
                }],
            },
        };
    }

    @computed
    get dataRules() {
        return toJS(this._dataRules);
    }

    @computed
    get roleSelectOpts() {
        let data = [{
            id: -1,
            value: '所有',
        }];
        this._roles && this._roles.forEach(item => {
            data.push({
                id: item.id,
                value: item.name,
            });
        });
        return data;
    }

    @computed
    get organizationTree() {
        return toJS(this._organizationTree);
    }

    @computed
    get firstUserGroupOpts() {
        let data = [{
            id: -1,
            value: '所有',
        }];
        this._firstUserGroup && this._firstUserGroup.forEach(item => {
            data.push({
                id: item.material_group_id || item.group_id,
                value: item.material_group_name || item.group_name,
            });
        });
        return data;
    }

    @computed
    get secondUserGroups() {
        return toJS(this._secondUserGroups);
    }

    @computed
    get firstMaterialGroupOpts() {
        let data = [{
            id: -1,
            value: '所有',
        }];
        this._firstMaterialGroup && this._firstMaterialGroup.forEach(item => {
            data.push({
                id: item.material_group_id || item.group_id,
                value: item.material_group_name || item.group_name,
            });
        });
        return data;
    }

    @computed
    get secondMaterialGroups() {
        return toJS(this._secondMaterialGroups);
    }

    @computed
    get categories() {
        return toJS(this._categories);
    }

    @computed
    get categoryOpts() {
        let data = [{
            id: -1,
            value: '全部类别',
        }];
        this._categories && this._categories.forEach(item => {
            data.push({
                id: item.id,
                value: item.name,
            });
        });
        return data;
    }

    @action
    destroy() {
        [
            '_dataRules',
            '_roles',
            '_organizationTree',
            '_firstUserGroup',
            '_firstMaterialGroup',
            '_secondUserGroups',
            '_secondMaterialGroups',
            '_categories',
            'ruleType',
            'resourceId',
            'resourceName',
            'bizCode',
            // 'categoryId',
        ].forEach(item => this[item] = null);
    }


    @action
    async init() {
        const ruleType = this.ruleType;
        if (ruleType === USER_DATA_RULE) {
            this.resourceId = 1;
            this.resourceName = '用户管理';
            this.bizCode = [1, 2, 3];
        } else if (ruleType === ORGANIZATION_DATA_RULE) {
            this.resourceId = 2;
            this.resourceName = '组织机构管理';
            this.bizCode = [1, 2, 3];
        } else if (ruleType === MATERIAL_DATA_RULE) {
            this.resourceId = 3;
            this.resourceName = '物资列表';
            this.bizCode = [1];
        } else if (ruleType === MATERIAL_ORGANIZATION_RELATION_DATA_RULE) {
            this.resourceId = 4;
            this.resourceName = '关联组织机构';
            this.bizCode = [1];
        } else if (ruleType === MANAGE_SCHEDULE) {
            this.resourceId = 5;
            this.resourceName = '排班管理';
            this.bizCode = [1, 2, 3];
        }
        this._dataRules = [this.generateNewDataRuleItem()];
        this.fetchRoles();
        this.fetchOrganizationTree();
        if (ruleType === MATERIAL_DATA_RULE) {
            this.fetchCategories();
        }
        await this.fetchDetail();
        this.fetchFirstGroup(1);
        if (ruleType === MATERIAL_DATA_RULE) {
            this.fetchFirstGroup(2);
        }
        const firstUserGroupIdSet = new Set();
        const firstMaterialIdSet = new Set();
        this.dataRules.forEach(rule => {
            const {
                data_rule_person,
                data_rule_material,
            } = rule;

            if (!data_rule_person.material_group || data_rule_person.material_group.length < 1) {
                data_rule_person.material_group = [{
                    first_group_id: -1,
                    second_group_id: -1,
                }];
            } else {
                // 左边列只有人员组
                data_rule_person.material_group.forEach(group => {
                    group.first_group_id > 0 && firstUserGroupIdSet.add(group.first_group_id);
                });
            }

            if (ruleType === ORGANIZATION_DATA_RULE || ruleType === MATERIAL_ORGANIZATION_RELATION_DATA_RULE) {
                data_rule_material.type = 2;
            } else {

                if (!data_rule_material.material_group || data_rule_material.material_group.length < 1) {
                    data_rule_material.material_group = [{
                        first_group_id: -1,
                        second_group_id: -1,
                    }];
                } else {
                    // 右边列需要区分人员组合物资组
                    data_rule_material.material_group.forEach(group => {
                        if (group.first_group_id > 0) {
                            if (ruleType === MATERIAL_DATA_RULE) {
                                firstMaterialIdSet.add(group.first_group_id);
                            } else {
                                firstUserGroupIdSet.add(group.first_group_id);
                            }
                        }
                    });
                }

                if (ruleType === MATERIAL_DATA_RULE) {
                    if (!data_rule_material.data_rule_material_ext || data_rule_material.data_rule_material_ext.length < 1) {
                        data_rule_material.data_rule_material_ext = [{
                            category_id: -1,
                            attr_id: -1,
                            attr_option_ids: [],
                        }];
                    } else {
                        data_rule_material.data_rule_material_ext.forEach(extItem => {
                            if (!extItem.category_id) {
                                extItem.category_id = -1;
                            }
                            if (!extItem.attr_id) {
                                extItem.attr_id = -1;
                            }
                            if (!extItem.attr_option_ids || extItem.attr_option_ids.length < 1) {
                                extItem.attr_option_ids = [];
                            } else {
                                extItem.attr_option_ids = extItem.attr_option_ids.filter(optId => optId > 0);
                            }
                        });
                    }
                }
            }
        });
        runInAction(() => {
            this._dataRules = this.dataRules;
        });
        for (let firstGroupId of firstUserGroupIdSet.keys()) {
            this.fetchSecondGroup(1, firstGroupId);
        }
        for (let firstGroupId of firstMaterialIdSet.keys()) {
            this.fetchSecondGroup(2, firstGroupId);
        }
    }

    @action
    addItem(idx) {
        if (idx < 0) {
            return;
        }
        this._dataRules.splice(idx + 1, 0, this.generateNewDataRuleItem());
    }

    @action
    deleteItem(idx) {
        if (idx < 0) {
            return;
        }
        this._dataRules.splice(idx, 1);
    }

    @action
    changeConfig(idx, key, val) {
        let data = this.dataRules;
        if (!data || !data[idx]) {
            return;
        }
        const arrKey = key.split('.');
        let targetData = data[idx];
        for (let i = 0, len = arrKey.length; i < len; i++) {
            const k = arrKey[i];
            const isArray = k.indexOf('[') !== -1;
            const isObject = k.indexOf('{') !== -1;
            if (isArray || isObject) {
                let [realKey, idx] = k.split(/[\[\]\{\}]/);
                if (isArray) {
                    idx = parseInt(idx, 10);
                }
                if (!targetData[realKey]) {
                    targetData[realKey] = isArray ? [] : {};
                }
                if (i === len - 1) {
                    // 最终项
                    targetData[realKey][idx] = val;
                } else {
                    if (!targetData[realKey][idx]) {
                        targetData[realKey][idx] = {};
                    }
                    targetData = targetData[realKey][idx];
                    console.log(targetData)
                }
            } else {
                if (i === len - 1) {
                    // 最终项
                    targetData[k] = val;
                    if (k === 'type') {
                        // 更改类型
                        if (val === 2) {
                            // 组织机构
                            if (!targetData.dep_ids) {
                                targetData.dep_ids = [];
                            }
                        } else if (val === 3) {
                            // 自定义分组
                            if (!targetData.material_group || targetData.material_group.length < 1) {
                                targetData.material_group = [{
                                    first_group_id: -1,
                                    second_group_id: -1,
                                }];
                            }
                            targetData.material_group.forEach(mg => {
                                if (!mg.first_group_id) {
                                    mg.first_group_id = -1;
                                }
                                if (!mg.second_group_id) {
                                    mg.second_group_id = -1;
                                }
                            });
                        }
                    } else if (k === 'category_id') {
                        // 重置属性及属性值
                        targetData['attr_id'] = -1;
                        targetData['attr_option_ids'] = [];
                    } else if (k === 'attr_id') {
                        // 重置属性值
                        targetData['attr_option_ids'] = [];
                    }
                } else {
                    if (!targetData[k]) {
                        targetData[k] = {};
                    }
                    targetData = targetData[k];
                }
            }
        }
        this._dataRules = data;
    }

    @action
    async fetchDetail() {
        const res = await this.post('/mm/data-rule/config/query', {
            resource_id: this.resourceId,
            resource_name: this.resourceName,
            biz_code: this.bizCode,
        }, {
            showGlobalLoading: true
        });
        runInAction(() => {
            if (res.code === '0000') {
                const data = res.data.data_rule && res.data.data_rule.length > 0 ? res.data.data_rule : [this.generateNewDataRuleItem()];
                this._dataRules = data;
            }
        });
    }

    /**
     * 角色列表
     */
    @action
    async fetchRoles() {
        const res = await this.get(`/auth/all-roles`, {
            type: 0
        }, {
            showGlobalLoading: true
        });
        runInAction(() => {
            if (res.code === '0000') {
                this._roles = res.data;
            }
        });
    }

    /**
     * 一级分组
     */
    @action
    async fetchFirstGroup(type) {
        let params = {};
        if (type === 1) {
            // 人员组
            params.group_type = '2,3';
        } else {
            // 物资组
            params.group_type = '1,3';
        }
        let url = '/mm/operation/material/groups-first';
        // if (this.categoryId) {
        //     url = '/mm/operation/material-group-first';
        //     params.category_id = this.categoryId;
        // }
        const res = await this.get(url, params, {
            showGlobalLoading: true
        });
        runInAction(() => {
            if (res.code === '0000') {
                this[type === 1 ? '_firstUserGroup' : '_firstMaterialGroup'] = res.data;
            }
        });
    }

    /**
     * 二级分组
     */
    @action
    async fetchSecondGroup(type, firstGroupId) {
        let secondGroups = this[type === 1 ? 'secondUserGroups' : 'secondMaterialGroups'] || {};
        if (firstGroupId < 1 || secondGroups[firstGroupId]) {
            return;
        }
        const res = await this.get('/mm/operation/material-group-second', {
            first_group_id: firstGroupId,
        }, {
            showGlobalLoading: true
        });
        runInAction(() => {
            if (res.code === '0000') {
                secondGroups[firstGroupId] = res.data;
                this[type === 1 ? '_secondUserGroups' : '_secondMaterialGroups'] = secondGroups;
            }
        });
    }

    /**
     * 组织机构树
     */
    @action
    async fetchOrganizationTree() {
        const res = await this.get('/organization/orz-trees', {
            with_default_node: 1,
        }, {
            showGlobalLoading: true,
        });
        runInAction(() => {
            if (res.code === '0000') {
                this._organizationTree = res.data && res.data.trees || [];
            }
        });
    }

    /**
     * 物资类型
     */
    @action
    async fetchCategories() {
        const res = await this.get(`/mm/categories`, {
            biz_code: 1,
            page: 1,
            per_page: 50,
            with_attr_option: 1,
        }, {
            showGlobalLoading: true
        });
        runInAction(() => {
            if (res.code === '0000' && res.data.data) {
                this._categories = res.data.data || [];
            }
        });
    }

    @action
    async submit() {
        if (!this.dataRules || this.dataRules.length < 1) {
            return;
        }
        let data = {
            resource_id: this.resourceId,
            resource_name: this.resourceName,
            data_rule: this.dataRules,
            biz_code: this.bizCode,
        };
        let data_rule = [];
        let hasError = false;
        data.data_rule.forEach(rule => {
            const {
                data_rule_person,
                data_rule_material,
            } = rule;
            if (!data_rule_person || !data_rule_material) {
                hasError = true;
                return;
            }
            if (data_rule_person.type === 1) {
                delete data_rule_person.dep_ids;
                delete data_rule_person.material_group;
            } else if (data_rule_person.type === 2) {
                delete data_rule_person.material_group;
            } else if (data_rule_person.type === 3) {
                delete data_rule_person.dep_ids;
            }

            if (data_rule_material.type === -1) {
                delete data_rule_material.dep_ids;
                delete data_rule_material.material_group;
            } else if (data_rule_material.type === 1) {
                delete data_rule_material.is_manager_default_dept;
                delete data_rule_material.dep_ids;
                delete data_rule_material.material_group;
            } else if (data_rule_material.type === 2) {
                delete data_rule_material.material_group;
            } else if (data_rule_material.type === 3) {
                delete data_rule_material.dep_ids;
            }
            if (this.ruleType !== MATERIAL_DATA_RULE) {
                delete data_rule_material.data_rule_material_ext;
            } else {
                if (data_rule_material.data_rule_material_ext) {
                    data_rule_material.data_rule_material_ext.forEach(extItem => {
                        if (!extItem.category_id) {
                            extItem.category_id = -1;
                        }
                        if (!extItem.attr_id) {
                            extItem.attr_id = -1;
                        }
                        if (!extItem.attr_option_ids || extItem.attr_option_ids.length < 1) {
                            extItem.attr_option_ids = [-1];
                        }
                    });
                }
            }
        });
        return await this.post('/mm/data-rule/config-saveorupdate', data, {
            showGlobalLoading: true
        });
    }
}

export default new Store();